package message.handler;

import message.annotation.MsgHandler;
import message.utils.XmlUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@MsgHandler(name = "xml")
public class XmlMsgHandler extends BaseHandler {

    @Override
    public void doPack(Map source) throws Exception {
        Map data = new HashMap();
        packDataToMap(this.msgConfig.getDocumentElement(), data, source);
        String xml = XmlUtils.createXmlByMap(this.msgConfig.getRootName(),
                data, this.msgConfig.getEncoding());
        this.msgData = xml.getBytes(this.msgConfig.getEncoding());
    }

    @Override
    protected void doUnPack(byte[] rspByte) throws Exception {
        String xml = new String (rspByte, this.msgConfig.getEncoding());
        Map result = new HashMap();
        Map<String, Object> source = (Map<String, Object>) XmlUtils.parseXmlToData(xml).get(this.msgConfig.getRootName());
        unPackDataToMap(this.msgConfig.getDocumentElement(), result, source);
        this.unPackResult = result;
    }


    @Override
    public void packInit() {

    }

    @Override
    public void unPackInit() {

    }
}
